package com.atguigu.Flink.datastream.transform;

import com.alibaba.fastjson.JSON;
import com.atguigu.Flink.POJO.Event;
import com.atguigu.Flink.POJO.WordCount;
import com.atguigu.Flink.function.ClickSource;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink02_ImplementFunction {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> ds = env.readTextFile("Input/words.txt");
         ds.flatMap(new MyFunction(" "))
                .keyBy(WordCount::getWord)
                .sum("count")
                .print();



        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //自定义函数类
    public static  class MyFunction implements FlatMapFunction<String, WordCount>{
        private String flag ;

        public MyFunction(String flag) {
            this.flag = flag;
        }

        @Override
        public void flatMap(String s, Collector<WordCount> collector) throws Exception {
            String[] value = s.split(flag);
            for (String s1 : value) {
                collector.collect(new WordCount(s1,1L));
            }
        }
    }
}
